Lists in Python
⮚
Ordered Collections: Lists are used to store a sequence of items in a specific order. These items can be of different data types (integers, strings, floats, booleans, or even other lists).
⮚
Mutable: Unlike strings or tuples, lists are mutable, meaning you can modify their contents after creation. This flexibility makes them well-suited for dynamic data manipulation.
⮚
Duplicate Values Allowed: Lists can contain duplicate elements, allowing you to represent repeated occurrences within your data set.
Creating Lists
Here are several methods to create lists in Python, explained without plagiarism:
Square Brackets ([]) (Most Common):
The most straightforward way to create a list is to enclose the elements within square brackets, separated by commas.
Creating list using square brackets [] in python
fruits = ["apple", "banana", "orange"]
numbers = [1, 2, 3.14, 42]
mixed_list = ["hello", 5, True]
print(fruits,numbers,mixed_list)
Output
['apple', 'banana', 'orange'] [1, 2, 3.14, 42] ['hello', 5, True]
List Constructor (list()) (Alternative Syntax):
While not as common, you can use the list() constructor to create an empty list or convert an iterable (like a string or tuple) into a list.
Creating list using list() constructor in python
empty_list = list() # Equivalent to []
string_as_list = list("hello")
print(string_as_list)
Output
['h', 'e', 'l', 'l', 'o']
List Comprehensions (Concise Creation):
List comprehensions offer a compact way to generate lists based on existing sequences or expressions. They often involve iterating over a range or another list.
Creating list using range in python
squared_numbers = [x**2 for x in range(1, 6)]
even_numbers = [x for x in range(10) if x % 2 == 0]
print(squared_numbers,even_numbers)
Output
[1, 4, 9, 16, 25] [0, 2, 4, 6, 8]
Key Points and Considerations
⮚ Remember that indexing in Python starts from 0, so the first element is at index 0, the second at index 1, and so on.
⮚ To access or modify elements within a list, use square brackets [] with the desired index.
⮚ Lists are versatile data structures that can be used to represent various types of collections, from shopping lists to complex data sets.
⮚ Choose the creation method that best suits your specific use case and coding style.